#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import time
import utils
import xmmsclient
from PyQt4 import QtGui, QtCore
from constants import *
from xmmsclient.collections import *

def debug(routine, message=""):
    print >>sys.stderr, "[%s] error! %s" % (routine, message)



class PlaylistModel(QtGui.QStandardItemModel):
    """Plain playlist model based on QStringListModel
    """
    _currentPos = 0
    
    def __init__(self, xmms2, playlistName=None):
        QtGui.QStandardItemModel.__init__(self)
        self.setHorizontalHeaderLabels(["playlist"])
        self.xmms2 = xmms2
        self.playlistName = playlistName
        self.format = "%n - %t (%d)\n    %l \n    by %a"
        self.loadPlaylist(playlistName)
        self.xmms2.broadcast_playlist_current_pos(self.currentPos)
        self.xmms2.broadcast_playlist_changed(self.updatePlaylist)

    def currentPos(self, res):
        if res.iserror(): return debug("currentPos", "error!")
        info = res.value()
        position = info["position"]
        playlistName = info["name"]
        item = self.item(self._currentPos)
        font = item.font()
        font.setBold(False)
        item.setFont(font)
        if self.playlistName is not None and self.playlistName != playlistName:
            return
        item = self.item(int(position))
        font = item.font()
        font.setBold(True)
        item.setFont(font)
        self._currentPos = position

    def dropMimeData(self, data, action, row, column, parent):
        #Reimplements drag and drop within the model.
        #Instead of "moving" rows directly, we request the server to do so and
        #then perform the model's rows  permutations according to
        #broadcast_playlist_changed signals. 
        
        if action == QtCore.Qt.IgnoreAction: return False
        if not data.hasFormat(u"text/plain"): return False
        if row != -1: beginRow = row
        elif parent.isValid(): beginRow = parent.row()
        else: beginRow = self.rowCount()
        indexes = [int(i) for i in data.text().split(",")]
        posFlag = 0
        for position in indexes:
            if position < beginRow:
                position += posFlag
                posFlag -= 1
            elif position >= beginRow:
                beginRow += 1
            print "moving", position, "to", beginRow - 1
            self.xmms2.playlist_move(position, beginRow - 1)
        return True
        
    def loadPlaylist(self, playlistName):
        icon = QtGui.QIcon()
        image = QtGui.QImage()
        pixmap = QtGui.QPixmap()
        def appendToPlaylist(res):
            #def setIcon(res):
            #    if res.iserror(): return debug("loadPlaylist",
            #                                   "Could not retrieve info!")
            #    data = res.value()
            #    image.loadFromData(QtCore.QByteArray(data))
            #    pixmap2 = pixmap.fromImage(image)
            #    icon.addPixmap(pixmap2)
            #    entry = QtGui.QStandardItem(icon, line)
                #self.appendRow([entry])
                ####UUUUUUUgly. We must change it!
                #try: 
                #    self.xmms2.playlist_current_pos(playlistName,
                #                                    self.currentPos)
                #except:
                #    pass
            if res.iserror(): return debug("loadPlaylist",
                                         "Could not retrieve info!")
            info = res.value()
            line = utils.squeeze(info, self.format)
            self.appendRow([QtGui.QStandardItem(line)])
            #self.insertRow(self.rowCount())
            #index = self.index(self.rowCount() - 1)
            #self.setData(index, QtCore.QVariant(line))
            #try:
            #    coverHash = info["picture_front"]
            #    self.xmms2.bindata_retrieve(coverHash, setIcon)
            #except KeyError:
            #    entry = QtGui.QStandardItem(line)
            #    self.appendRow([entry,
            #                    QtGui.QStandardItem(id)])
                #try: 
                #    self.xmms2.playlist_current_pos(playlistName,
                #                                self.currentPos)
                #except:
                #    pass
        def queryInfo(res):
            if res.iserror(): return debug("loadPlaylist",
                                         "Could not query info!")
            for id in res.value():
                self.xmms2.medialib_get_info(id, appendToPlaylist)
            self.xmms2.playlist_current_pos(playlistName, self.currentPos)
        self.xmms2.playlist_list_entries(playlistName, cb=queryInfo)
    
    def mimeData(self, indexes):
        """Returns a QMimeData containing a string with selected rows separated
        by commas.
        """
        mimeData = QtCore.QMimeData()
        draggedRows = ""
        for index in indexes:
            if index.isValid():
                draggedRows = ','.join([draggedRows, unicode(index.row())])
        mimeData.setText(draggedRows[1:])
        return mimeData

    def mimeTypes(self):
        #Our drag and drop is commited by retrieving rows indexes and
        #asking the server to move playlist entries
        return QtCore.QStringList(u"text/plain")

    def updatePlaylist(self, res):
        if res.iserror(): return debug("updatePlaylist")
        info = res.value()
        if self.playlistName is not None and self.playlistName != info["name"]:
            return
        signalType = info["type"]
        if signalType == xmmsclient.PLAYLIST_CHANGED_ADD:
            position = info["position"]
            id = info["id"]
            def addToPlaylist(res):
                if res.iserror(): return debug("addToPlaylist")
                info = res.value()
                line = utils.squeeze(info, self.format)
                self.insertRow(position, [QtGui.QStandardItem(line)])
                if position < self._currentPos: self._currentPos += 1
            self.xmms2.medialib_get_info(id, addToPlaylist)
        elif signalType == xmmsclient.PLAYLIST_CHANGED_REMOVE:
            position = info["position"]
            if self._currentPos > position: self._currentPos -= 1
            self.removeRow(position)
        elif signalType == xmmsclient.PLAYLIST_CHANGED_CLEAR:
            self.clear()
            self._currentPos = 0
        elif signalType == xmmsclient.PLAYLIST_CHANGED_MOVE:
            position = info["position"]
            newPosition = info["newposition"]
            row = self.takeRow(position)
            self.insertRow(newPosition, row)



if __name__ == "__main__":
    import xmmsqt4
    app = QtGui.QApplication(sys.argv)
    xmms = xmmsclient.XMMS("a")
    xmms.connect()
    xmmsqt4.XMMSConnector(xmms, app)
    pl = PlaylistModel(xmms)
    plview = QtGui.QListView()
    plview.setModel(pl)
    plview.show()
    sys.exit(app.exec_())


    
